$(document).ready(function() {

	//Selectors
	var FORM = $('#page-form');
	var FORM_INPUTS = $('FORM :input');
	var ALERTS = $('.alert');
	var RESULT = $('#result');
	var SUBMIT_BUTTON = $('#submit');
	var RETAKE_BUTTON = $('#retake');
	var ALERT_SAVING = $('#page-saving');
	var ALERT_SUCCESS = $('#save-success');
	var ALERT_ERROR = $('#save-error');
	
	/* Listeners */
	SUBMIT_BUTTON.on('click', function(event) {
		
		// Abort any pending request
		if (request) {
			request.abort();
		}

		// Hide information
		ALERT_ERROR.hide();
		ALERT_SUCCESS.hide();

		//Show progress bar
		ALERT_SAVING.show()


		//Update editor
		for ( instance in CKEDITOR.instances ) {
     		CKEDITOR.instances[instance].updateElement();
     	}

		// Serialize the data in the form
		var serializedData = FORM.serialize();

		// Disable the inputs for the duration of the ajax request
		FORM_INPUTS.prop("disabled", true);

		// Send the request to the forms action path
		var request = $.post(
			FORM.attr('action'), 
			serializedData, 
			function(response) {
				// log the response to the console
				console.log("Response: "+response);
			}
		);

		// Callback handler that will be called on success
		request.done(function (response, textStatus, jqXHR){	
			//viewCorrectedTest(response);
			ALERT_SAVING.hide();
			ALERT_SUCCESS.show();
			var title = document.getElementById('title');
			document.getElementById('page-title').innerHTML = "Edit Page<small> "+title.value+"</small>"; 
		});

		// Callback handler that will be called on failure
		request.fail(function (jqXHR, textStatus, errorThrown){
			var response = String(jqXHR.responseText);
			var mt = String("missing_title");
			if (response == mt)
			{
				document.getElementById('save-error').innerHTML = "<strong>Error!</strong> Please fill in a title.";
			}

			ALERT_SAVING.hide();
			ALERT_ERROR.show();
			// log the error to the console
			console.error("The following error occured: " + 
				textStatus, errorThrown
			);
		});

		// Callback handler that will be called regardless
		// if the request failed or succeeded
		request.always(function () {
			// Reenable the inputs
			FORM_INPUTS/*.not(SUBMIT_BUTTON)*/.prop("disabled", false);
		});

		// Prevent default posting of form
		event.preventDefault();
		
	});
	
	RETAKE_BUTTON.on('click', function() {
		
		location.reload();
		
	});
	
});